<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
      >
        添加品牌
      </el-button>
      <el-table style="margin: 10px 0px" border :data="trademarkArr">
        <el-table-column
          label="序号"
          width="80px"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="default"
              @click="updataTrademark(row)"
              icon="Edit">
            </el-button>
            <el-popconfirm :title="`确认删除${ row.tmName }?`" @confirm="removeTrademark(row.id)">
              <template #reference>
                <el-button
                    type="danger"
                    size="default"
                    @click=""
                    icon="Delete">
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="getHasTrademark"
        @size-change="sizeChange"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 6, 9, 12]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id?'修改品牌':'添加品牌'">
      <el-form :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName"> 
          <el-input placeholder="输入品牌名称" v-model="trademarkParams.tmName "/>
        </el-form-item>
        <el-form-item label="品牌Logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="true"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
        <el-button type="danger" size="default" @click="cancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref,reactive,nextTick } from 'vue'
import { reqHasTrademark,reqAddOrUpdateTrademark, reqDeleteTrademake } from '../../../api/product/trademark'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark
} from '../../../api/product/trademark/type'
import { error, log } from 'console'
import { ElMessage, UploadProps } from 'element-plus';
import { get } from 'http';

let pageNo = ref<number>(1)
let limit = ref<number>(3)
let total = ref<number>(0)
let trademarkArr = ref<Records>([])
let dialogFormVisible = ref<boolean>(false)
let trademarkParams=reactive<TradeMark>({
  tmName:'',
  logoUrl:''
})
let formRef=ref()
const visible = ref(false)
onMounted(() => {
  getHasTrademark()
})
const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}

const sizeChange = () => {
  getHasTrademark()
}

const addTrademark = () => {
  trademarkParams.tmName=''
  trademarkParams.logoUrl=''
  trademarkParams.id=undefined
  dialogFormVisible.value = true
  nextTick(()=>{
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

const updataTrademark = (row:any) => {
  nextTick(()=>{
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  dialogFormVisible.value = true
  // trademarkParams.tmName=row.tmName
  // trademarkParams.logoUrl=row.logoUrl
  // trademarkParams.id=row.id
  Object.assign(trademarkParams,row)
  
}

const cancel=()=>{
    dialogFormVisible.value=false
    
}

const confirm=async ()=>{
    await formRef.value.validate()
    let result:any=await reqAddOrUpdateTrademark(trademarkParams)
    if(result.code==200){
      dialogFormVisible.value=false
      ElMessage({
        type:'success',
        message:trademarkParams.id?'修改成功':'添加成功'
      })
  
      getHasTrademark(trademarkParams.id?pageNo.value:1)
    }else{
      ElMessage({
        type:'error',
        message:trademarkParams.id?'修改失败':'添加失败'
      })
      dialogFormVisible.value=false 
    }
    
}

const beforeAvatarUpload:UploadProps['beforeUpload']=(rawFile)=>{
  if(rawFile.type=='image/png'||rawFile.type=='image/jpeg'||rawFile.type=='image/gif'){
      if(rawFile.size/1024/1024<4){
        return true
      }else{
        ElMessage({
          type:'error',
          message:'图片大小超过4M'
        })
        return false
      }
  }else{
    ElMessage({
      type:'error',
      message:'上传图片格式类型为PNG||JPG||GIF'
    })
    return false
  }
  
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  trademarkParams.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}

const validataTmName=(rule:any,value:any,callBack:any)=>{
  if(value.trim().length>0){
    callBack()
  }else{
    callBack(new Error('品牌名称不能为空') )
  }
}

const validataLogoUrl=(rule:any,value:any,callBack:any)=>{
  if(value){
    callBack()
  }else{
    callBack(new Error('图片未上传'))
  }
  
}
const rules={
  tmName:[{required:true,trigger:'blur',validator:validataTmName}],
  logoUrl:[{required:true,validator:validataLogoUrl }]
}
const removeTrademark=async (id:number)=>{
  let result=await reqDeleteTrademake(id)
  if(result.code==200){
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    getHasTrademark(trademarkArr.value.length>1?pageNo.value:pageNo.value-1)
  }else{
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
